import { useMap } from 'ahooks';
import { forwardRef, useImperativeHandle, useMemo, useState } from 'react';
import Source from './Entity/Source';
import { SelectSourceProps, SelectSourceRef } from './interface';
import { ThreeSpanLayout } from './Layout';
import { LeftGroupMenu, LeftGroupMenuPorps } from './LeftMenu';
import { MainSearchTable } from './MainSearchTable';
import { MainSearchTableProps } from './MainSearchTable/interface';
import { usePreset } from './Presets';
import { SelectedTable } from './SelectedTable';

export const ModalContent = forwardRef<SelectSourceRef, SelectSourceProps>(function _ModalContent(
  { modalWidth, preSet = '单选题选择', defaultValue = [], params = {}, columnsRender, menuLeftWidth },
  ref,
) {
  /**
   * @desc 根据预设的menu配置，选择合适的menu
   */
  const presetMenu = usePreset(preSet, params, columnsRender);

  // 生成左侧树的配置相关数据，是否显示及菜单内容
  const { leftShow, menuItems } = useMemo(() => {
    return {
      menuItems: Array.isArray(presetMenu) ? presetMenu : [presetMenu],
      // 左侧菜单是否需要显示,如果只有一个菜单则不需要显示
      leftShow: Array.isArray(presetMenu) ? menuLeftWidth : 0,
    };
  }, [presetMenu]);

  // 选中内容
  const [map, mapSet] = useMap<string, Source>(defaultValue.map((v) => [v.id, v]));

  // 当前选中的菜单
  const [menuKey, setMenuKey] = useState(() => {
    let arr: NonNullable<LeftGroupMenuPorps['items']> | null = menuItems.slice();
    while (arr?.length) {
      const node = arr.shift();
      if (node) {
        if ('children' in node) {
          arr.push(...node.children);
        } else {
          arr = null;
          return node.key;
        }
      }
    }
  });

  // 展示选中的核心表格内容
  const [childs, setChilds] = useState(() => {
    let arr: NonNullable<LeftGroupMenuPorps<{ props: MainSearchTableProps }>['items']> | null = menuItems.slice();
    while (arr?.length) {
      const node = arr.shift();
      if (node) {
        if ('children' in node) {
          arr.push(...node.children);
        } else if (node.key === menuKey) {
          arr = null;
          return [
            {
              key: node.key,
              props: node.props,
            },
          ];
        }
      }
    }
    return [];
  });

  useImperativeHandle(
    ref,
    () => {
      return {
        submit() {
          return [...map.values()];
        },
        getActiveMenuKey() {
          return menuKey!;
        },
      };
    },
    [map],
  );

  return (
    <ThreeSpanLayout totalWidth={modalWidth} leftWidth={leftShow}>
      {/* 左侧菜单 */}
      <LeftGroupMenu
        value={menuKey}
        onChange={(menuItem) => {
          setMenuKey(menuItem.key);
          if (!childs.some((v) => v.key === menuItem.key)) {
            setChilds((v) => {
              return [...v, { key: menuItem.key, props: menuItem.props }];
            });
          }
          //如果是计划模版来的，课件包和试卷不能混合切换菜单的时候清空右侧选中项
          // if (preSet == '已上架课件' && menuItem.key != menuKey) {
          //   map.clear();
          // }
          const oldItem = menuItems.find((e) => e.key === menuKey);
          if (oldItem && 'group' in oldItem) {
            if (oldItem.group !== menuItem.group) {
              map.clear();
            }
          }
        }}
        items={menuItems}
      />
      {/* 中间选择内容 */}
      <ul style={{ height: '100%' }}>
        {childs.map((child) => {
          return (
            <li style={{ height: '100%' }} key={child.key} hidden={menuKey !== child.key}>
              <MainSearchTable value={map} valueSet={mapSet} {...child.props} />
            </li>
          );
        })}
      </ul>
      {/* 右侧选中项目 */}
      <SelectedTable value={map} valueSet={mapSet} menuKey={menuKey} />
    </ThreeSpanLayout>
  );
});
